package yxy.game.pm2.active.command.bottlewish;

import yxy.apple.util.RandomUtility;
import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.actwish;
import yxy.cherry.data.bean.actwishdata;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.active.module.ActiveModule_心愿瓶;
import yxy.game.pm2.active.module.subordinateclass.Act_许愿瓶大奖纪录;
import yxy.game.pm2.active.module.subordinateclass.ghost.GhostRandom;
import yxy.game.pm2.active.module.subordinateclass.ghost.GhostWishRandom;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.ServerBean;
import yxy.game.pm2.bean.currency.Currencies;
import yxy.game.pm2.bean.currency.CurrencyType;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.BottleWishMessage;
import yxy.game.pm2.message.PackageMessage;
import yxy.game.pm2.module.CurrencyHandle;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/****************************************
 * @name CMD_Active_心愿瓶_BottleWish
 * @description 心愿瓶活动许愿操作
 * @author 梁健彬
 * @since 2022-08-22
 ***************************************/
@MessageType(proto = Command.BottleWish, classtype = BottleWishMessage.BottleWishRequest.class)
public class CMD_Active_心愿瓶_BottleWish extends Command<BottleWishMessage.BottleWishRequest> {

    @Override
    public void execute(MessageSource messageSource, BottleWishMessage.BottleWishRequest request) throws Exception {
        String playercode = messageSource.getTag();
        int times = request.getTimes();
        BottleWishMessage.BottleWishResponse.Builder response = BottleWishMessage.BottleWishResponse.newBuilder();
        ActiveModule_心愿瓶 am = ActiveModule_心愿瓶.get(playercode, false);
        Result result = Result.Success;
        try {

            if (am == null) {
                send(messageSource, response, Result.ActNoOpen);
                return;
            }

            if (!am.running()) {
                send(messageSource, response, Result.ActNoOpen);
                return;
            }

            //todo 许愿逻辑
            if (am.tryLock()) {
                result = summonHero(am, times, playercode, response);
            }

            //todo 瓶子的信息
            HashMap<Integer, Integer> bottle = am.getBottle();
            Map<String, actwish> allData = DataCenter.getAllData(actwish.class);
            for (actwish value : allData.values()) {
                BottleWishMessage.BottleMsg.Builder builder = BottleWishMessage.BottleMsg.newBuilder();
                builder.setDataId(value.getId());
                builder.setValue(bottle.get(value.getId()));
                builder.setCanRewardValue(value.getConversionScore());
                Currencies curs = new Currencies(Currency.create(value.getRewardtype(), value.getRewardid(), value.getRewardnum()));
                Collection<PackageMessage.Item> items = new CurrencyHandle().packItems(curs);
                builder.addAllItem(items);
                response.addBottles(builder);
            }

            //todo 大奖日志
            PlayerBean pb = PlayerBean.get(playercode);
            ServerBean sb = ServerBean.get(pb.getServerId());
            response.addAllAwardsInfo(am.getLog(sb.getAreaId()));

            send(messageSource, response, result);
        } catch (Exception e) {
            e.printStackTrace();
            send(messageSource, response, Result.DataError);
        } finally {
            am.unlock();
        }
    }

    private void send(MessageSource messageSource, BottleWishMessage.BottleWishResponse.Builder response, Result result) {
        response.setResult(result.packResult());
        MessageEmitterHandler.getInstance().send(messageSource, response.build());
    }

    /**
     * 许愿逻辑
     *
     * @param am
     * @param times
     * @param response
     * @return
     */
    private Result summonHero(ActiveModule_心愿瓶 am, int times, String playercode, BottleWishMessage.BottleWishResponse.Builder response) {
        switch (times) {
            case 1:
                break;
            case 10:
                break;
            default:
                return Result.ParamError;
        }

        PlayerBean pb = PlayerBean.get(playercode);
        ServerBean sb = ServerBean.get(pb.getServerId());
        ArrayList<GhostRandom> grs = new ArrayList<>();                 //所有物品的权重
        actwishdata data = DataCenter.getData(1, actwishdata.class);//小垃圾表
        Currency cost = Currency.create(data.getCosttype(), data.getCostid(), data.getCostnum() * times);//花费
        Map<String, actwish> allData = DataCenter.getAllData(actwish.class);//瓶子表
        HashMap<Integer, ArrayList<GhostWishRandom>> scoreList = new HashMap<>();           //所有瓶子许愿值增加的权重

        if (Currency.number(playercode, CurrencyType.forNumber(data.getCosttype()), data.getCostid(), false) < data.getCostnum() * times) {
            return Result.PackItemNumberLack;// 数量不够
        }

        for (actwish value : allData.values()) {
            ArrayList<GhostWishRandom> list = new ArrayList<>();
            for (int i = 0; i < value.getWeight().length; i++) {
                if (value.getWeight()[i] == 0) continue;
                list.add(new GhostWishRandom(value.getScore()[i], value.getWeight()[i]));
            }
            scoreList.put(value.getId(), list);
        }

        for (int i = 0; i < data.getRewardtype().length; i++) {
            if (data.getRewardtype()[i] == 0) continue;
            Currency cur = Currency.create(data.getRewardtype()[i], data.getRewardid()[i], data.getRewardnum()[i]);
            GhostRandom gr = new GhostRandom(cur, data.getCounter()[i]);
            grs.add(gr);
        }

        //开始抽奖
        ArrayList<Currency> curs = new ArrayList<Currency>();
        for (int i = 0; i < times; i++) {
            GhostRandom gr = RandomUtility.randomWeight(grs);    //权重随机
            curs.add(gr.getCur());

            //每次抽奖每个许愿瓶对应加许愿值
            addWish(am, allData, scoreList);

            //大奖记录,上传到抽奖日志
            if (gr.getWeight() <= data.getMaincounter()) {
                Act_许愿瓶大奖纪录 msg = Act_许愿瓶大奖纪录.create(sb.getAreaId(), pb.getName(), gr.getCur());
                msg.add();
            }
        }

        //消费
        try {
            new CurrencyHandle().cost(playercode, CCReason.心愿瓶, cost);
        } catch (Exception e) {
            return Result.CostFail;
        }

        Collection<PackageMessage.Item> items = new CurrencyHandle().packItems(curs);
        new CurrencyHandle().addCurrency(playercode, CCReason.心愿瓶, curs);
        response.addAllItem(items);
        am.set();
        return Result.Success;
    }


    /**
     * 增加瓶子许愿值
     *
     * @param am
     */
    public void addWish(ActiveModule_心愿瓶 am, Map<String, actwish> allData, HashMap<Integer, ArrayList<GhostWishRandom>> scoreList) {
        HashMap<Integer, Integer> bottle = am.getBottle();
        for (actwish data : allData.values()) {
            ArrayList<GhostWishRandom> list = scoreList.get(data.getId());
            GhostWishRandom random = RandomUtility.randomWeight(list);//权重随机
            Integer totalWish = bottle.get(data.getId());
            bottle.put(data.getId(), totalWish + random.getScore());
        }
    }
}
